//package com.runa.monitor.platinterface.platService;
//
//import com.runa.monitor.comm.dto.Collector;
//import com.runa.monitor.comm.dto.DataTransmission;
//import com.runa.monitor.comm.dto.DataTransmissionProtocol;
//import com.runa.monitor.comm.dto.OpcServer;
//import com.runa.monitor.platinterface.netservice.base.BaseContainer;
//import com.runa.monitor.platinterface.netservice.base.async.FutureDataTask;
//import com.runa.monitor.platinterface.netservice.equipment.*;
//import com.runa.monitor.platinterface.netservice.server.ConnectorServer;
//import com.runa.monitor.platinterface.netservice.server.ListenerServer;
//import com.runa.monitor.platinterface.netservice.server.OpcConnectServer;
//import com.runa.monitor.platinterface.backwork.impl.NetStatusCallbackImpl;
//import com.runa.monitor.platinterface.backwork.util.RabbitMqUtil;
//import com.runa.persistence.dao.HeatNetRepository;
//import com.runa.protocol.enums.DtuModel;
//import com.runa.protocol.enums.ModbusType;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.boot.CommandLineRunner;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.Resource;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//
///**
// * @author zhuj
// */
////@Service
//public class MonitorService implements CommandLineRunner {
//
//    private static final Logger logger = LoggerFactory.getLogger(MonitorService.class);
//
//    @Value("${comm-server.heatnet.tcp-async}")
//    private boolean tcpAsync;
//
//    @Value("${comm-server.heatnet.enable}")
//    private boolean key;
//
//    @Resource
//    private RabbitMqUtil rabbitMqUtil;
//
//    @Resource
//    private HeatNetRepository heatNetRepository;
//
//    @Resource(name = "ancFutureTask")
//    private FutureDataTask<Map<Integer, String>> task;
//
//    @Override
//    public void run(String... args) {
//        try {
//            if (key) {
//                initHnApplication();
//            }
//        } catch (Exception e) {
//            logger.error("热网通信初始化错误——", e);
//        }
//    }
//
////    /**
////     * 热网初始化
////     */
////    private void initHnApplication() {
////        //创建网络状态变更回调
////        BaseContainer.setNetStatusCallback(newComm NetStatusCallbackImpl(rabbitMqUtil));
////        //获取采集器原始数据
////        Map<OpcServer, List<PlcService>> opcMap = newComm HashMap<>();
////        List<NormalPlcService> normalPlcServices = takePlcService(heatNetRepository.getAll(), opcMap);
////        //创建连接
////        createConnector(normalPlcServices);
////        //创建opc服务
////        createOpcConnector(opcMap);
////    }
//
//
//    private List<NormalPlcService> takePlcService(List<Collector> collectors, Map<OpcServer, List<PlcService>> opcMap) {
//        List<NormalPlcService> normalPlcServices = newComm ArrayList<>();
//        try {
//            for (Collector collector : collectors) {
//                PlcService plcService = null;
//                if ("DTU".equals(collector.getType())) {
//                    DataTransmission dataTransmission = heatNetRepository.getDataTransmissionById(collector.getDataTransmissionId());
//                    if (dataTransmission == null) {
//                        logger.debug("collector：{},找不到相应的数传模块,{}", collector.getId(), collector.getDataTransmissionId());
//                        continue;
//                    }
//                    DataTransmissionProtocol dtp = heatNetRepository.getDtpById(dataTransmission.getDtpId());
//                    if (dtp == null) {
//                        logger.debug("数传：{},找不到相应的通讯协议,{}", dataTransmission.getSerialNo(), dataTransmission.getDtpId());
//                        continue;
//                    }
//                    DtuModel dtuModel = null;
//                    try {
//                        dtuModel = DtuModel.valuesOf(dtp.getProtocol());
//                    } catch (Exception e) {
//                        logger.error("{} {} ", collector.getSubject(), collector.getId(), e);
//                    }
//                    plcService = newComm PublicDtuPlcService(collector.getId(), collector.getSubject(), collector.getEquAddr(), dataTransmission.getSerialNo(),
//                            collector.getRegisterCount(), collector.getTimeout(), ModbusType.valueIs(collector.getProtocol()), dtuModel, task, createListener(dtp));
//                } else if ("PLC".equals(collector.getType())) {
//                    logger.info("PLC address --- {}", collector.getIp() + ":" + collector.getPort());
//                    ModbusType type = ModbusType.valueIs(collector.getProtocol());
//                    if (type == ModbusType.S7) {
//                        plcService = newComm SmsPlcService(collector.getId(), collector.getSubject(), collector.getEquAddr(), collector.getRegisterCount(),
//                                tcpAsync, collector.getTimeout(), ModbusType.valueIs(collector.getProtocol()), collector.getIp(), collector.getPort(), task);
//                    } else {
//                        plcService = newComm NormalPlcService(collector.getId(), collector.getSubject(), collector.getEquAddr(), collector.getRegisterCount(),
//                                tcpAsync, collector.getTimeout(), ModbusType.valueIs(collector.getProtocol()), collector.getIp(), collector.getPort(), task);
//                    }
//                    normalPlcServices.add((NormalPlcService) plcService);
//                } else if ("OPC".equals(collector.getType())) {
//                    OpcPlcService ops = (OpcPlcService) BaseContainer.getPlcService(
//                            String.join("#", collector.getId().toString(), collector.getSubject()));
//                    if (ops != null && opcMap == null) {
//                        ops.init(heatNetRepository.getByCollectorOrderAddress(
//                                String.join("#", collector.getId().toString(), collector.getSubject())));
//                        //如果该plc没有点位
//                        if (ops.getServer() != null) {
//                            ops.getServer().addItems(ops.getVariables());
//                        }
//                    } else {
//                        if (collector.getOpcId() == null) {
//                            continue;
//                        }
//                        OpcServer opcServer = heatNetRepository.getOpcById(collector.getOpcId());
//                        plcService = newComm OpcPlcService(collector.getId(), collector.getSubject(), task);
//                        if (opcMap.get(opcServer) != null) {
//                            opcMap.get(opcServer).add(plcService);
//                        } else {
//                            List<PlcService> list = newComm ArrayList<>();
//                            list.add(plcService);
//                            opcMap.put(opcServer, list);
//                        }
//                    }
//                }
//                if (plcService != null) {
//                    try {
//                        plcService.init(heatNetRepository.getByCollectorOrderAddress(
//                                String.join("#", collector.getId().toString(), collector.getSubject())));
//                        BaseContainer.putPlcService(plcService);
//                    } catch (Exception e) {
//                        logger.error("{} {} ", plcService.getSubject(), plcService.getId(), e);
//                    }
//                }
//            }
//        }catch (Exception e){
//            logger.debug("PLCService ERROR:{}", ExceptionUtils.getFullStackTrace(e));
//        }
//        return normalPlcServices;
//    }
//
//    private ListenerServer createListener(DataTransmissionProtocol protocol) {
//        return ListenerServer.getInstance(protocol.getProtocol(), ModbusType.valueIs(protocol.getModbusType()), protocol.getPort());
//    }
//
//    private void createConnector(List<NormalPlcService> services) {
//        for (NormalPlcService service : services) {
//            try {
//                newComm ConnectorServer(service);
//            } catch (Exception e) {
//                logger.error("PLC {} {} 创建连接失败", service.getSubject(), service.getId(), e);
//            }
//        }
//    }
//
//    private void createOpcConnector(Map<OpcServer, List<PlcService>> opcMap) {
//        for (Map.Entry<OpcServer, List<PlcService>> entry : opcMap.entrySet()) {
//            OpcServer opcServer = entry.getKey();
//            OpcConnectServer ocs = null;
//            try {
//                ocs = newComm OpcConnectServer(
//                        opcServer.getIp() + (opcServer.getPort() == null ? "" : ":" + opcServer.getPort()),
//                        opcServer.getUsername(), opcServer.getPassword(), opcServer.getAppName(), opcServer.getAppId());
//
//            } catch (Exception e) {
//                logger.error("Create OPC Server ", e);
//            }
//            if (ocs != null) {
//                for (PlcService temp : entry.getValue()) {
//                    OpcPlcService ops = (OpcPlcService) temp;
//                    ocs.addItems(ops.getVariables());
//                    ops.setServer(ocs);
//                }
//            }
//        }
//    }
//
//    public void updatePlcService(String subject, List<Integer> ids) {
//        closeLink(subject, ids);
//        List<Collector> collectors = heatNetRepository.getCollectors(
//                ids.stream().map(I -> String.join("#", I.toString(), subject)).collect(Collectors.toList()));
//        List<NormalPlcService> normalPlcServices = takePlcService(collectors, null);
//        createConnector(normalPlcServices);
//    }
//
//    private void closeLink(String subject, List<Integer> ids) {
//        for (Integer id : ids) {
//            PlcService service = BaseContainer.getPlcService(String.join("#", id.toString(), subject));
//            if (service != null && service.session() != null) {
//                if (!service.session().closeAndRemove()) {
//                    logger.error("PLC {} {} 移除session失败", subject, service.getId());
//                }
//            }
//        }
//    }
//
//}
